package com.ayf.payment.game.api.service.impl;

import com.ayf.payment.game.api.dto.*;
import com.ayf.payment.game.api.dto.criteria.LowerMerchantCriteria;
import com.ayf.payment.game.api.dto.criteria.MerchantCriteria;
import com.ayf.payment.game.api.dto.platform.*;
import com.ayf.payment.game.api.dto.platform.criteria.MerchantAccountCriteria;
import com.ayf.payment.game.api.dto.platform.criteria.MerchantAccountPageCriteria;
import com.ayf.payment.game.api.entity.*;
import com.ayf.payment.game.api.entity.platform.MerchantSettleRate;
import com.ayf.payment.game.api.entity.platform.PaymentProduct;
import com.ayf.payment.game.api.exception.ParameterException;
import com.ayf.payment.game.api.mapper.*;
import com.ayf.payment.game.api.mapper.platform.MerchantSettleRateMapper;
import com.ayf.payment.game.api.mapper.platform.PaymentProductMapper;
import com.ayf.payment.game.api.service.MerchantRepository;
import com.ayf.payment.game.api.service.MerchantService;
import com.ayf.payment.game.api.service.TokenService;
import com.ayf.payment.game.api.type.MerchantStatus;
import com.ayf.payment.game.api.type.Status;
import com.ayf.payment.game.api.type.YesAndNo;
import com.ayf.payment.game.api.utils.DateUtils;
import com.ayf.payment.game.api.utils.KeyUtil;
import com.ayf.payment.game.api.utils.MD5Util;
import com.ayf.payment.game.api.utils.RandomStrUtils;
import com.swwx.charm.commons.lang.utils.BeanConvertUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MerchantServiceImpl implements MerchantService {

    @Resource
    private MerchantMapper merchantMapper;

    @Resource
    private MerchantAccountMapper merchantAccountMapper;

    @Resource
    private MerchantConfigMapper merchantConfigMapper;

    @Resource
    private MerchantProxyRelMapper merchantProxyRelMapper;

    @Resource
    private IpWhiteListMapper ipWhiteListMapper;

    @Resource
    private MerchantSettleRateMapper merchantSettleRateMapper;

    @Resource
    private ProxyGroupMapper proxyGroupMapper;

    @Resource
    private ProxyGroupRateMapper proxyGroupRateMapper;

    @Resource
    private ProxyNetConfigMapper proxyNetConfigMapper;

    @Resource
    private MerchantSettleRateCustomMapper merchantSettleRateCustomMapper;

    @Resource
    private PaymentProductMapper paymentProductMapper;

    @Resource
    private MerchantRepository merchantRepository;

    @Resource
    private MerchantSonMapper merchantSonMapper;

    @Resource
    private MerchantRoleMapper merchantRoleMapper;

    @Resource
    private MerchantRolePermissionMapper merchantRolePermissionMapper;

    @Autowired
    private TokenService tokenService;

    @Override
    public MerchantDTO selectOne(Merchant merchant) {
        if (merchant == null) {
            throw new ParameterException("商户信息不能为空");
        }
        Merchant db = merchantMapper.selectOne(merchant);
        if (db == null) {
            throw new ParameterException("商户不存在");
        }
        MerchantDTO dto = BeanConvertUtils.convert(db, MerchantDTO.class);
        if (StringUtils.isNotEmpty(db.getPayPassword())) {
            dto.setIsHavePayPwd("YES");
        } else {
            dto.setIsHavePayPwd("NO");
        }
        return dto;
    }

    @Override
    public Merchant find(Integer id) {
        Merchant merchant = new Merchant();
        merchant.setId(id);
        return merchantMapper.selectOne(merchant);
    }

    @Override
    public boolean update(Merchant merchant) {
        if (merchant == null) {
            throw new ParameterException("商户信息不能为空");
        }
        if (merchant.getId() == null) {
            throw new ParameterException("商户主键不能为空");
        }
        return merchantMapper.updateByPrimaryKeySelective(merchant) > 0;
    }

    @Override
    public boolean register(MerchantCriteria merchantCriteria) {
        if (merchantCriteria == null) {
            throw new ParameterException("注册信息不能为空");
        }
        if (StringUtils.isBlank(merchantCriteria.getLoginAccount()) || StringUtils.isBlank(merchantCriteria.getPassword()) || StringUtils.isBlank(merchantCriteria.getRepeatPassword())) {
            throw new ParameterException("登录名称、登录密码、确认密码不能为空");
        }
        if (StringUtils.isBlank(merchantCriteria.getPhone())) {
            throw new ParameterException("手机号不能为空");
        }
        if (!StringUtils.equals(merchantCriteria.getRepeatPassword(), merchantCriteria.getPassword())) {
            throw new ParameterException("两次密码不一样");
        }
        Merchant temp = new Merchant();
        temp.setLoginAccount(merchantCriteria.getLoginAccount());
        MerchantSon merchantSon=new MerchantSon();
        merchantSon.setLoginAccount(merchantCriteria.getLoginAccount());
        if (merchantMapper.selectOne(temp) != null || merchantSonMapper.selectOne(merchantSon) != null) {
            throw new ParameterException("登录名称重复");
        }
        String salt = RandomStrUtils.createRandom(false, 8);
        Merchant merchant = BeanConvertUtils.convert(merchantCriteria, Merchant.class);
        merchant.setSalt(salt);
        merchant.setPassword(MD5Util.sign(merchantCriteria.getPassword(), salt));
        Map<String, String> key = KeyUtil.genKey();
        merchant.setPublicKey(key.get(KeyUtil.PUBLIC_KEY));
        merchant.setPrivateKey(key.get(KeyUtil.PRIVATE_KEY));
        merchant.setLoginTime(DateUtils.getNowDate());
        merchant.setIdCardValidityTimeType(0);
        //添加商户信息
        if (merchantMapper.insertSelective(merchant) > 0) {
            //初始化商户配置信息
            MerchantConfig merchantConfig = new MerchantConfig();
            merchantConfig.setMerchantId(merchant.getId());
            //查询出默认费率
            MerchantSettleRateDTO info = merchantSettleRateMapper.selectDefaultRateInfo();
            merchantConfig.setSettleIdentificationId(info.getId());
            merchantConfigMapper.insertSelective(merchantConfig);
            //初始化商户自定义费率表
            List<MerchantSettleRateCustom> list = new ArrayList<>();
            for (MerchantSettleRateConfigDTO config : info.getConfigList()) {
                MerchantSettleRateCustom rateCustom = new MerchantSettleRateCustom();
                rateCustom.setMerchantId(merchant.getId());
                rateCustom.setRateId(info.getId());
                rateCustom.setPayProductId(config.getPayProductId());
                if (config.getProductStatus() == 1) {
                    rateCustom.setStatus(Status.ENABLE);
                } else {
                    rateCustom.setStatus(Status.PROHIBIT);
                }
                list.add(rateCustom);
            }
            merchantSettleRateCustomMapper.insertBatch(list);
            //初始化商户账户信息
            MerchantAccount merchantAccount = new MerchantAccount();
            merchantAccount.setMerchantId(merchant.getId());
            merchantAccount.setBalance(new BigDecimal(0));
            merchantAccount.setCashWithdrawal(new BigDecimal(0));
            merchantAccount.setFreezing(new BigDecimal(0));
            merchantAccountMapper.insertSelective(merchantAccount);
            //初始化商户IP白名单
            IpWhiteList ipWhiteList = new IpWhiteList();
            ipWhiteList.setMerchantId(merchant.getId());
            ipWhiteListMapper.insertSelective(ipWhiteList);

            MerchantRole merchantRole = new MerchantRole();
            merchantRole.setMerchantId(merchant.getId());
            merchantRole.setRoleStatus(1);
            merchantRole.setRemark("游戏推广员");
            merchantRole.setCode("TuiG");
            merchantRole.setName("推广员");
            merchantRoleMapper.insertSelective(merchantRole);
            MerchantRolePermission merchantRolePermission=new MerchantRolePermission();
            merchantRolePermission.setRoleId(merchantRole.getId());
            merchantRolePermission.setPermissionId(17);
            merchantRolePermissionMapper.insertSelective(merchantRolePermission);
            return true;
        }
        return false;
    }

    @Override
    public MerchantLoginDTO login(MerchantCriteria merchantCriteria) {
        MerchantLoginDTO dto = new MerchantLoginDTO();
        dto.setType("FAIL");
        if (merchantCriteria == null) {
            throw new ParameterException("账号不能为空");
        }
        if (merchantCriteria.getLoginAccount() == null) {
            throw new ParameterException("账号不能为空");
        }
        if (merchantCriteria.getPassword() == null) {
            throw new ParameterException("密码不能为空");
        }
        Merchant merchant = new Merchant();
        merchant.setLoginAccount(merchantCriteria.getLoginAccount());
        Merchant dbMerchant = merchantMapper.selectOne(merchant);
        if (dbMerchant == null) {
            MerchantSon merchantSon = new MerchantSon();
            merchantSon.setLoginAccount(merchantCriteria.getLoginAccount());
            MerchantSon dbMerchantSon = merchantSonMapper.selectOne(merchantSon);
            if (dbMerchantSon == null) {
                throw new ParameterException("账号或密码错误");
            } else {
                if (dbMerchantSon.getStatus() == 0) {
                    throw new ParameterException("当前子账号已被禁用");
                }
                if (dbMerchantSon.getPassword().equals(MD5Util.sign(merchantCriteria.getPassword(),
                        dbMerchantSon.getSalt()))) {
                    dto.setType("SON");
                    dto.setMerchantSon(BeanConvertUtils.convert(dbMerchantSon, MerchantSonDTO.class));
                } else {
                    throw new ParameterException("账号或密码错误");
                }
            }
        } else {
            String sign = MD5Util.sign(merchantCriteria.getPassword(), dbMerchant.getSalt());
            if (dbMerchant.getPassword().equals(sign)) {
                if (dbMerchant.getStatus().name().equals(MerchantStatus.PROHIBIT.name())) {
                    throw new ParameterException("当前商户已被禁用");
                } else if (dbMerchant.getStatus().name().equals(MerchantStatus.AUDITED.name())) {
                    throw new ParameterException("请等待运营人员审核");
                }
                if (dbMerchant.getStatus().name().equals(MerchantStatus.DELETE.name())) {
                    throw new ParameterException("账号或密码错误");
                }
                dto.setType("FATHER");
                dto.setMerchant(BeanConvertUtils.convert(dbMerchant, MerchantDTO.class));
            } else {
                throw new ParameterException("账号或密码错误");
            }
        }
        return dto;
    }

    @Override
    public boolean updatePassword(MerchantCriteria merchantCriteria) {
        if (merchantCriteria == null) {
            throw new ParameterException("修改信息不能为空");
        }
        if (merchantCriteria.getOriginalPassword() == null) {
            throw new ParameterException("原始密码密码不能为空");
        }
        if (merchantCriteria.getPassword() == null) {
            throw new ParameterException("新密码不能为空");
        }
        if (merchantCriteria.getRepeatPassword() == null) {
            throw new ParameterException("确认密码不能为空");
        }
        if (!StringUtils.equals(merchantCriteria.getRepeatPassword(), merchantCriteria.getPassword())) {
            throw new ParameterException("新密码与确认密码不一样");
        }
        Merchant merchant = merchantMapper.selectByPrimaryKey(merchantCriteria.getId());
        if (!merchant.getPassword().equals(MD5Util.sign(merchantCriteria.getOriginalPassword(), merchant.getSalt()))) {
            throw new ParameterException("原始密码输入错误");
        }
        Merchant temp = new Merchant();
        temp.setPassword(MD5Util.sign(merchantCriteria.getPassword(), merchant.getSalt()));
        temp.setId(merchant.getId());
        return merchantMapper.updateByPrimaryKeySelective(temp) > 0;
    }

    @Override
    public boolean resetPassword(MerchantCriteria merchantCriteria) {
        if (StringUtils.isBlank(merchantCriteria.getLoginAccount())) {
            throw new ParameterException("商户账号不能为空");
        }
        if (merchantCriteria.getPassword() == null) {
            throw new ParameterException("新密码不能为空");
        }
        if (merchantCriteria.getRepeatPassword() == null) {
            throw new ParameterException("确密码不能为空");
        }
        if (!StringUtils.equals(merchantCriteria.getRepeatPassword(), merchantCriteria.getPassword())) {
            throw new ParameterException("新密码与确认密码不一致");
        }
        String salt = RandomStrUtils.createRandom(false, 8);
        merchantCriteria.setSalt(salt);
        merchantCriteria.setPassword(MD5Util.sign(merchantCriteria.getPassword(), salt));
        return merchantMapper.resetPassword(merchantCriteria) > 0;
    }

    @Override
    public List<MerchantDTO> selectAll(MerchantCriteria merchantCriteria) {
        return merchantMapper.selectAllMerchant(merchantCriteria);
    }

    @Override
    public List<AuditedMerchantDTO> selectAuditedMerchant() {
        return merchantMapper.selectAuditedMerchant();
    }

    @Override
    public boolean updateMerchantType(MerchantCriteria merchantCriteria) {
        if (merchantCriteria == null) {
            throw new ParameterException("修改信息不能为空");
        }
        if (merchantCriteria.getId() == null) {
            throw new ParameterException("商户ID不能为空");
        }
        Merchant merchant = new Merchant();
        merchant.setId(merchantCriteria.getId());
        Merchant dbMerchant = merchantMapper.selectByPrimaryKey(merchantCriteria.getId());
        //判断商户是否为普通商户
        if ("GENERAL".equals(dbMerchant.getMerchantType())) {
            merchant.setMerchantType("PROXY");
            merchantMapper.updateByPrimaryKeySelective(merchant);
            //初始化代理商网站配置
            ProxyNetConfig proxyNetConfig = new ProxyNetConfig();
            proxyNetConfig.setMerchantId(merchant.getId());
            proxyNetConfigMapper.insertSelective(proxyNetConfig);
            merchantRepository.del(dbMerchant.getId());
            return true;
        } else if ("PROXY".equals(dbMerchant.getMerchantType())) { //判断商户是否为代理商户
            //查询出代理商户所有下级商户ID
            List<Integer> ids = selectIds(merchantCriteria.getId());
            ids.add(merchantCriteria.getId());
            //批量更新商户类型为普通商户
            merchantMapper.updateMerchantTypes(ids);
            //删除代理商户与下级商户的关系
            merchantProxyRelMapper.deleteByMerchantId(merchantCriteria.getId());
            //更改费率为默认费率
            Integer rateId = updateRateCustom(ids);
            merchantConfigMapper.updateIdentificationId(ids, rateId);
            //删除代理商网站配置
            ProxyNetConfig proxyNetConfig = new ProxyNetConfig();
            proxyNetConfig.setMerchantId(merchant.getId());
            proxyNetConfigMapper.delete(proxyNetConfig);
            //删除代理商分组信息
            ProxyGroup proxyGroup = new ProxyGroup();
            proxyGroup.setMerchantId(merchantCriteria.getId());
            List<ProxyGroup> groupList = proxyGroupMapper.select(proxyGroup);
            if (groupList != null && groupList.size() > 0) {
                List<Integer> groupIds = new ArrayList<>();
                for (ProxyGroup group : groupList) {
                    groupIds.add(group.getId());
                }
                proxyGroupRateMapper.deleteRatesByGroupIds(groupIds);
                proxyGroupMapper.delete(proxyGroup);
            }
            ids.forEach((mId)->{
                merchantRepository.del(mId);
            });
            return true;
        } else if ("LOWER".equals(dbMerchant.getMerchantType())) {
            //更新商户类型为普通商户
            merchant.setMerchantType("GENERAL");
            merchantMapper.updateByPrimaryKeySelective(merchant);
            //删除代理商户与下级商户的关系
            merchantProxyRelMapper.deleteByLowerId(merchantCriteria.getId());
            MerchantConfig merchantConfig = new MerchantConfig();
            merchantConfig.setMerchantId(dbMerchant.getId());
            MerchantConfig config = merchantConfigMapper.selectOne(merchantConfig);
            proxyGroupMapper.updateGroupMerchantNum(config.getSettleIdentificationId(), -1);
            //更改商户费率
            List<Integer> ids = new ArrayList<>();
            ids.add(merchant.getId());
            //更改费率为默认费率
            Integer rateId = updateRateCustom(ids);
            merchantConfigMapper.updateIdentificationId(ids, rateId);
            merchantRepository.del(config.getMerchantId());
            return true;
        }
        return false;
    }

    private Integer updateRateCustom(List<Integer> ids) {
        //查询出默认费率
        MerchantSettleRate rate = new MerchantSettleRate();
        rate.setIsFirst((short) 1);
        MerchantSettleRate settleRate = merchantSettleRateMapper.selectOne(rate);
        //初始化商户自定义费率表
        merchantSettleRateCustomMapper.updateMerchantRateId(null, ids, settleRate.getId());
        return settleRate.getId();
    }

    @Override
    public boolean deleteMerchant(Integer merchantId) {
        if (merchantId == null) {
            throw new ParameterException("商户ID不能为空");
        }
        MerchantConfig merchantConfig = new MerchantConfig();
        merchantConfig.setMerchantId(merchantId);
        Merchant merchant = merchantMapper.selectByPrimaryKey(merchantId);
        if (merchant.getMerchantType().equals("LOWER")) {
            //删除代理商户与下级商户的关系
            merchantProxyRelMapper.deleteByLowerId(merchantId);
            //分组下商户数量减一
            MerchantConfig config = merchantConfigMapper.selectOne(merchantConfig);
            proxyGroupMapper.updateGroupMerchantNum(config.getSettleIdentificationId(), -1);
        }
        //删除基本信息
        merchantMapper.deleteByPrimaryKey(merchantId);
        //删除配置信息
        merchantConfigMapper.delete(merchantConfig);
        //删除ip白名单
        IpWhiteList ipWhiteList = new IpWhiteList();
        ipWhiteList.setMerchantId(merchantId);
        ipWhiteListMapper.delete(ipWhiteList);
        //删除商户账户表
        MerchantAccount merchantAccount = new MerchantAccount();
        merchantAccount.setMerchantId(merchantId);
        merchantAccountMapper.delete(merchantAccount);
        //删除商户自定义结算周期
        MerchantSettleRateCustom merchantSettleRateCustom = new MerchantSettleRateCustom();
        merchantSettleRateCustom.setMerchantId(merchantId);
        merchantSettleRateCustomMapper.delete(merchantSettleRateCustom);
        return true;
    }

    @Override
    public boolean insertLowerMerchant(LowerMerchantCriteria lowerMerchantCriteria) {
        if (lowerMerchantCriteria == null) {
            throw new ParameterException("注册信息不能为空");
        }
        if (StringUtils.isBlank(lowerMerchantCriteria.getLoginAccount()) || StringUtils.isBlank(lowerMerchantCriteria.getPassword()) || StringUtils.isBlank(lowerMerchantCriteria.getRepeatPassword())) {
            throw new ParameterException("登录名称、登录密码、确认密码不能为空");
        }
        if (StringUtils.isBlank(lowerMerchantCriteria.getPhone())) {
            throw new ParameterException("手机号不能为空");
        }
        if (!StringUtils.equals(lowerMerchantCriteria.getRepeatPassword(), lowerMerchantCriteria.getPassword())) {
            throw new ParameterException("两次密码不一样");
        }
        if (lowerMerchantCriteria.getMerchantId() == null) {
            throw new ParameterException("代理商ID不能为空");
        }
        if (lowerMerchantCriteria.getGroupId() == null) {
            ProxyGroup proxyGroup = new ProxyGroup();
            proxyGroup.setMerchantId(lowerMerchantCriteria.getMerchantId());
            proxyGroup.setDefaults(YesAndNo.YES);
            ProxyGroup group = proxyGroupMapper.selectOne(proxyGroup);
            if (group == null) {
                throw new ParameterException("该代理商暂无默认分组，请联系代理商创建默认分组");
            }
            lowerMerchantCriteria.setGroupId(group.getId());
        }
        Merchant temp = new Merchant();
        temp.setLoginAccount(lowerMerchantCriteria.getLoginAccount());
        MerchantSon merchantSon=new MerchantSon();
        merchantSon.setLoginAccount(lowerMerchantCriteria.getLoginAccount());
        if (merchantMapper.selectOne(temp) != null || merchantSonMapper.selectOne(merchantSon) != null) {
            throw new ParameterException("登录名称重复");
        }
        String salt = RandomStrUtils.createRandom(false, 8);
//        String paySalt = RandomStrUtils.createRandom(false,8);
        Merchant merchant = BeanConvertUtils.convert(lowerMerchantCriteria, Merchant.class);
        merchant.setSalt(salt);
        merchant.setPassword(MD5Util.sign(lowerMerchantCriteria.getPassword(), salt));
//        merchant.setPayPassword(MD5Util.sign(lowerMerchantCriteria.getPassword(),paySalt));
//        merchant.setPaySalt(paySalt);
        Map<String, String> key = KeyUtil.genKey();
        merchant.setPublicKey(key.get(KeyUtil.PUBLIC_KEY));
        merchant.setPrivateKey(key.get(KeyUtil.PRIVATE_KEY));
        merchant.setMerchantType("LOWER");
        merchant.setIdCardValidityTimeType(0);
        //添加商户信息
        if (merchantMapper.insertSelective(merchant) > 0) {
            //查询出代理商的费率配置id
            MerchantConfig tempConfig = new MerchantConfig();
            tempConfig.setMerchantId(lowerMerchantCriteria.getMerchantId());
            MerchantConfig proxyConfig = merchantConfigMapper.selectOne(tempConfig);
            //初始化商户配置信息
            MerchantConfig merchantConfig = new MerchantConfig();
            merchantConfig.setMerchantId(merchant.getId());
            merchantConfig.setNetName(lowerMerchantCriteria.getNetName());
            merchantConfig.setDomainName(lowerMerchantCriteria.getDomainName());
            merchantConfig.setSettleIdentificationId(lowerMerchantCriteria.getGroupId());
            merchantConfig.setProxyIdentificationId(proxyConfig.getSettleIdentificationId());
            merchantConfigMapper.insertSelective(merchantConfig);

            //查询出分组信息
            ProxyGroupRate proxyGroupRate = new ProxyGroupRate();
            proxyGroupRate.setGroupId(lowerMerchantCriteria.getGroupId());
            List<ProxyGroupRate> rateList = proxyGroupRateMapper.select(proxyGroupRate);
            //初始化商户自定义费率表
            List<MerchantSettleRateCustom> list = new ArrayList<>();
            for (ProxyGroupRate groupRate : rateList) {
                MerchantSettleRateCustom rateCustom = new MerchantSettleRateCustom();
                rateCustom.setRateId(groupRate.getGroupId());
                rateCustom.setPayProductId(groupRate.getPayProductId());
                rateCustom.setMerchantId(merchant.getId());
                PaymentProduct paymentProduct = paymentProductMapper.selectByPrimaryKey(groupRate.getPayProductId());
                if (paymentProduct.getProductStatus() == 1) {
                    rateCustom.setStatus(Status.ENABLE);
                } else {
                    rateCustom.setStatus(Status.PROHIBIT);
                }
                list.add(rateCustom);
            }
            merchantSettleRateCustomMapper.insertBatch(list);

            //初始化商户账户信息
            MerchantAccount merchantAccount = new MerchantAccount();
            merchantAccount.setMerchantId(merchant.getId());
            merchantAccount.setBalance(new BigDecimal(0));
            merchantAccount.setCashWithdrawal(new BigDecimal(0));
            merchantAccount.setFreezing(new BigDecimal(0));
            merchantAccountMapper.insertSelective(merchantAccount);
            //初始化商户IP白名单
            IpWhiteList ipWhiteList = new IpWhiteList();
            ipWhiteList.setMerchantId(merchant.getId());
            ipWhiteListMapper.insertSelective(ipWhiteList);
            //分组下商户数量加一
            proxyGroupMapper.updateGroupMerchantNum(lowerMerchantCriteria.getGroupId(), 1);
            //添加代理商户和下级商户的关系
            MerchantProxyRel merchantProxyRel = new MerchantProxyRel();
            merchantProxyRel.setLowerId(merchant.getId());
            merchantProxyRel.setMerchantId(lowerMerchantCriteria.getMerchantId());
            merchantProxyRelMapper.insertSelective(merchantProxyRel);

            MerchantRole merchantRole = new MerchantRole();
            merchantRole.setMerchantId(merchant.getId());
            merchantRole.setRoleStatus(1);
            merchantRole.setRemark("游戏推广员");
            merchantRole.setCode("TuiG");
            merchantRole.setName("推广员");
            merchantRoleMapper.insertSelective(merchantRole);
            MerchantRolePermission merchantRolePermission=new MerchantRolePermission();
            merchantRolePermission.setRoleId(merchantRole.getId());
            merchantRolePermission.setPermissionId(17);
            merchantRolePermissionMapper.insertSelective(merchantRolePermission);
            return true;
        }
        return false;
    }

    @Override
    public List<Integer> selectIds(Integer merchantId) {
        if (merchantId == null) {
            throw new ParameterException("商户id不能为空");
        }
        return merchantProxyRelMapper.selectLowerIds(merchantId);
    }

    @Override
    public List<Integer> selectProxyIds() {
        return merchantMapper.selectProxyIds();
    }

    @Override
    public List<LowerMerchantDTO> selectAllLower(LowerMerchantCriteria lower) {
        return merchantMapper.selectAllLower(lower);
    }

    @Override
    public LowerMerchantCriteria selectMerchantInfo(Integer merchantId) {
        if (merchantId == null) {
            throw new ParameterException("商户id不能为空");
        }
        return merchantMapper.selectMerchantInfo(merchantId);
    }

    @Override
    public boolean updateMerchantGroup(LowerMerchantCriteria lower) {
        if (lower.getGroupId() == null) {
            throw new ParameterException("分组id不能为空");
        }
        if (lower.getMerchantId() == null) {
            throw new ParameterException("商户id不能为空");
        }
        MerchantConfig merchantConfig = new MerchantConfig();
        merchantConfig.setMerchantId(lower.getMerchantId());
        MerchantConfig dbConfig = merchantConfigMapper.selectOne(merchantConfig);
        merchantConfig.setSettleIdentificationId(lower.getGroupId());
        merchantConfigMapper.updateConfigSelective(merchantConfig);
        proxyGroupMapper.updateGroupMerchantNum(dbConfig.getSettleIdentificationId(), -1);
        proxyGroupMapper.updateGroupMerchantNum(lower.getGroupId(), 1);
        merchantSettleRateCustomMapper.updateMerchantRateId(lower.getMerchantId(), null, lower.getGroupId());
        merchantRepository.del(lower.getMerchantId());
        return true;
    }

    @Override
    public boolean updateMerchantInfo(LowerMerchantCriteria lower) {
        if (lower == null) {
            throw new ParameterException("商户id不能为空");
        }
        if (StringUtils.isBlank(lower.getName())) {
            throw new ParameterException("联系人不能为空");
        }
        Merchant merchant = new Merchant();
        merchant.setId(lower.getMerchantId());
        merchant.setName(lower.getName());
        merchantMapper.updateByPrimaryKeySelective(merchant);
//        MerchantConfig merchantConfig = new MerchantConfig();
//        merchantConfig.setMerchantId(lower.getMerchantId());
//        merchantConfig.setNetName(lower.getNetName());
//        merchantConfig.setDomainName(lower.getDomainName());
//        merchantConfigMapper.updateConfigSelective(merchantConfig);
        return true;
    }

    @Override
    public List<SettleRateInfoDTO> selectRateInfo(Integer merchantId) {
        if (merchantId == null) {
            throw new ParameterException("商户ID不能为空");
        }
        Merchant merchant = merchantMapper.selectByPrimaryKey(merchantId);
        if ("LOWER".equals(merchant.getMerchantType())) {
            return merchantSettleRateCustomMapper.selectLowerRateInfo(merchantId);
        }
        return merchantSettleRateCustomMapper.selectRateInfo(merchantId);
    }

    @Override
    public boolean updateProductStatus(MerchantSettleRateCustom rateCustom) {
        if (rateCustom == null) {
            throw new ParameterException("产品信息不能为空");
        }
        if (rateCustom.getMerchantId() == null) {
            throw new ParameterException("商户ID不能为空");
        }
        if (rateCustom.getPayProductId() == null) {
            throw new ParameterException("支付产品id不能为空");
        }
        if (rateCustom.getStatus() == null) {
            throw new ParameterException("支付产品状态不能为空");
        }

        PaymentChannelDTO paymentChannelDTO = paymentProductMapper.getChannelStatusByProductId(rateCustom.getPayProductId());
        if (paymentChannelDTO == null) {
            throw new ParameterException("产品id传入错误");
        }
        if (paymentChannelDTO.getChannelFlag() == 0) {
            throw new ParameterException("当前产品所属通道为关闭状态，请先联系运营人员开启通道");
        }
        return merchantSettleRateCustomMapper.updateStatus(rateCustom) > 0;
    }

    @Override
    public MerchantDTO selectMerchantDTO(Integer merchantId) {
        return merchantMapper.selectMerchantDTO(merchantId);
    }

    @Override
    public MerchantCommonDTO getMerchantCommon(Integer merchantId) {
        return merchantMapper.getMerchantCommon(merchantId);
    }

    @Override
    public boolean checkPayPassword(Integer merchantId, String payPassword) {
        Merchant originMerchant = merchantMapper.selectByPrimaryKey(merchantId);
        if (originMerchant == null) {
            throw new ParameterException("商户ID[" + merchantId + "]不存在");
        }
        if (originMerchant.getPayPassword().equals(MD5Util.sign(payPassword, originMerchant.getPaySalt()))) {
            return true;
        }
        return false;
    }

    @Override
    public void upateMerchantLevel(Integer merchantId, Integer level) {
        Merchant merchant=new Merchant();
        merchant.setId(merchantId);
        merchant.setMerchantLevel(level);
        merchantMapper.updateByPrimaryKeySelective(merchant);
    }


    @Override
    public boolean updatePayPassword(MerchantCriteria merchantCriteria) {
        if (merchantCriteria == null) {
            throw new ParameterException("修改信息不能为空");
        }
        if (merchantCriteria.getOriginalPassword() == null) {
            throw new ParameterException("原支付密码不能为空");
        }
        if (merchantCriteria.getPassword() == null) {
            throw new ParameterException("新支付密码不能为空");
        }
        if (merchantCriteria.getRepeatPassword() == null) {
            throw new ParameterException("确认支付密码不能为空");
        }
        if (!StringUtils.equals(merchantCriteria.getRepeatPassword(), merchantCriteria.getPassword())) {
            throw new ParameterException("新支付密码与确认支付密码不一致");
        }
        Merchant merchant = merchantMapper.selectByPrimaryKey(merchantCriteria.getId());
        if (!merchant.getPayPassword().equals(MD5Util.sign(merchantCriteria.getOriginalPassword(), merchant.getPaySalt()))) {
            throw new ParameterException("原支付密码输入错误");
        }
        Merchant temp = new Merchant();
        temp.setPayPassword(MD5Util.sign(merchantCriteria.getPassword(), merchant.getPaySalt()));
        temp.setId(merchant.getId());
        return merchantMapper.updateByPrimaryKeySelective(temp) > 0;
    }

    @Override
    public boolean setLower(LowerMerchantCriteria lowerMerchantCriteria) {
        if (lowerMerchantCriteria.getMerchantId() == null) {
            throw new ParameterException("下级商户id不能为空");
        }
        if (lowerMerchantCriteria.getProxyId() == null) {
            throw new ParameterException("代理商id不能为空");
        }
        Merchant proxy = merchantMapper.selectByPrimaryKey(lowerMerchantCriteria.getProxyId());
        if (proxy == null) {
            throw new ParameterException("不存在此代理商");
        }
        if (!proxy.getMerchantType().equals("PROXY")) {
            throw new ParameterException("代理商id传入错误，该id不是代理商");
        }
        Merchant dbMerchant = merchantMapper.selectByPrimaryKey(lowerMerchantCriteria.getMerchantId());
        if (!dbMerchant.getMerchantType().equals("GENERAL")) {
            throw new ParameterException("商户id传入错误，该id不是普通商户");
        }
        Merchant merchant = new Merchant();
        merchant.setMerchantType("LOWER");
        merchant.setId(lowerMerchantCriteria.getMerchantId());
        merchantMapper.updateByPrimaryKeySelective(merchant);
        ProxyGroup proxyGroup = proxyGroupMapper.selectDefaultsGroup(lowerMerchantCriteria.getProxyId());
        if (proxyGroup == null) {
            throw new ParameterException("该代理商没有默认分组，请联系代理商创建默认分组");
        }
        //查询出代理商的费率配置id
        MerchantConfig tempConfig = new MerchantConfig();
        tempConfig.setMerchantId(lowerMerchantCriteria.getProxyId());
        MerchantConfig proxyConfig = merchantConfigMapper.selectOne(tempConfig);
        MerchantConfig merchantConfig = new MerchantConfig();
        merchantConfig.setSettleIdentificationId(proxyGroup.getId());
        merchantConfig.setMerchantId(lowerMerchantCriteria.getMerchantId());
        merchantConfig.setProxyIdentificationId(proxyConfig.getSettleIdentificationId());
        merchantConfigMapper.updateConfigSelective(merchantConfig);
        MerchantProxyRel merchantProxyRel = new MerchantProxyRel();
        merchantProxyRel.setMerchantId(lowerMerchantCriteria.getProxyId());
        merchantProxyRel.setLowerId(lowerMerchantCriteria.getMerchantId());
        merchantProxyRelMapper.insertSelective(merchantProxyRel);
        proxyGroupMapper.updateGroupMerchantNum(proxyGroup.getId(), 1);
        merchantSettleRateCustomMapper.updateMerchantRateId(lowerMerchantCriteria.getMerchantId(), null,
                proxyGroup.getId());
        merchantRepository.del(merchant.getId());
        return true;
    }

    @Override
    public boolean setPayPassword(MerchantCriteria merchantCriteria) {
        if (merchantCriteria == null) {
            throw new ParameterException("密码信息不能为空");
        }
        if (merchantCriteria.getPassword() == null) {
            throw new ParameterException("支付密码不能为空");
        }
        if (merchantCriteria.getRepeatPassword() == null) {
            throw new ParameterException("确认支付密码不能为空");
        }
        if (!StringUtils.equals(merchantCriteria.getRepeatPassword(), merchantCriteria.getPassword())) {
            throw new ParameterException("支付密码与确认支付密码不一致");
        }
        String paySalt = RandomStrUtils.createRandom(false, 8);
        Merchant temp = new Merchant();
        temp.setPaySalt(paySalt);
        temp.setPayPassword(MD5Util.sign(merchantCriteria.getPassword(), paySalt));
        temp.setId(merchantCriteria.getId());
        return merchantMapper.updateByPrimaryKeySelective(temp) > 0;
    }

    @Override
    public boolean untieMobile(Integer merchantId) {
        if (merchantId == null) {
            throw new ParameterException("商户id不能为空");
        }
        return merchantMapper.untieMobile(merchantId);
    }
    @Override
    public List<MerchantSettleDTO> getSettleList(Integer date, Integer merchantId) {
        return merchantMapper.getSettleList(date, merchantId);
    }

    @Override
    public MerchantAccountQueryDTO countMerchantAccount(MerchantAccountCriteria merchantAccountCriteria) {
        return merchantAccountMapper.countMerchantAccount(merchantAccountCriteria);
    }

    @Override
    public List<MerchantAccountDTO> merchantAccountList(MerchantAccountPageCriteria merchantAccountPageCriteria) {
        return merchantAccountMapper.merchantAccountList(merchantAccountPageCriteria);
    }

    @Override
    public boolean updateMerchantPwd(MerchantDTO dto) {
        if (dto == null){
            throw new ParameterException("参数不能为空");
        }
        if (dto.getId()==null){
            throw new ParameterException("商户ID不能为空");
        }
        if (StringUtils.isEmpty(dto.getMerchantPwdType())){
            throw new ParameterException("密码修改类型不能为空");
        }
        if (StringUtils.isEmpty(dto.getMerchantPwd())){
            throw new ParameterException("密码不能为空");
        }
        if (StringUtils.isEmpty(dto.getConfirmMerchantPwd())){
            throw new ParameterException("确认密码不能为空");
        }
        if (!StringUtils.equals(dto.getMerchantPwd(),dto.getConfirmMerchantPwd())){
            throw new ParameterException("密码与确认密码不一致");
        }
        Merchant merchant = merchantMapper.selectByPrimaryKey(dto.getId());
        if (merchant==null){
            throw new ParameterException("商户记录不存在");
        }
        if ("2".equals(dto.getMerchantPwdType())){//修改支付密码
            MerchantCriteria merchantCriteria = new MerchantCriteria();
            merchantCriteria.setId(dto.getId());
            merchantCriteria.setPassword(dto.getMerchantPwd());
            merchantCriteria.setRepeatPassword(dto.getConfirmMerchantPwd());
            return setPayPassword(merchantCriteria);
        } else if ("1".equals(dto.getMerchantPwdType())){//修改登录密码
            String paySalt = RandomStrUtils.createRandom(false, 8);
            Merchant temp = new Merchant();
            temp.setSalt(paySalt);
            temp.setPassword(MD5Util.sign(dto.getMerchantPwd(), paySalt));
            temp.setId(dto.getId());
            tokenService.deleteTokenByLoginId(dto.getId(), dto.getId());
            return merchantMapper.updateByPrimaryKeySelective(temp) > 0;
        }
        return false;
    }

    @Override
    public boolean updateMerchantAndMerchantConfig(Merchant merchant, MerchantConfig merchantConfig) {
        update(merchant);
        return merchantConfigMapper.updateConfigSelective(merchantConfig)>0;
    }
}
